package com.itheima.social.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.social.dto.SoDynamicDto;
import com.itheima.social.entity.SoDynamic;
import com.itheima.social.entity.SoFocus;
import com.itheima.social.service.SoDynamicService;
import com.itheima.social.common.R;
import com.itheima.social.entity.*;
import com.itheima.social.entity.SoLikes;
import com.itheima.social.service.SoFocusService;
import com.itheima.social.service.SoLikesService;
import com.itheima.social.service.SoUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/social/api")
@Slf4j
public class SoDynamicController {

    @Autowired
    private SoDynamicService soDynamicService;
    @Autowired
    private SoLikesService soLikesService;
    @Autowired
    private SoFocusService soFocusService;
    @Autowired
    private SoUserService soUserService;

    @Value("${social.path}")
    private String basePath;

    public String uploadPic(String pic) throws IOException {
        if (pic != null) {
            String[] parts = pic.split(",");
            String fileData = parts[1];
            byte[] fileBytes = Base64.getDecoder().decode(fileData.getBytes(StandardCharsets.UTF_8));
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateString = formatter.format(currentTime);
            Random random = new Random();
            int number = random.nextInt(90000) + 10000;
            String name = dateString + number + ".png";
            Files.write(Paths.get(basePath + name), fileBytes);
            return name;
        }
        return pic;
    }

    @PostMapping("/dynamic_api.php")
    @Transactional
    public R<Object> user_api(@RequestParam(required = false) String act,
                              @RequestParam(required = false) String desc,
                              @RequestParam(required = false) String pos,
                              @RequestParam(required = false) String tag,
                              @RequestParam(required = false) String pic1,
                              @RequestParam(required = false) String pic2,
                              @RequestParam(required = false) String pic3,
                              @RequestParam(required = false) String pn,
                              @RequestParam(required = false) String size,
                              @RequestParam(required = false) String uid,
                              @RequestParam(required = false) String did,
                              @RequestParam(required = false) String touid
    ) throws IOException {
        if (act != null) {
            if (act.equals("pub")) {
                SoDynamic soDynamic = new SoDynamic();

                long timeL = new Date().getTime();
                String s = Long.toString(timeL);
                String substring = s.substring(0, 10);
                int time=Integer.parseInt(substring);

                soDynamic.setDescs(desc);
                soDynamic.setPos(pos);
                soDynamic.setTag(tag);
                soDynamic.setAddtime(time);

                ArrayList<String> list = new ArrayList<>();
                if (pic1 != null) {
                    String name = uploadPic(pic1);
                    list.add(name);
                }
                if (pic2 != null) {
                    String name = uploadPic(pic2);
                    list.add(name);
                }
                if (pic3 != null) {
                    String name = uploadPic(pic3);
                    list.add(name);
                }

                Object[] arr = list.toArray();
                String arrStr = "";
                for (int i = 0; i < arr.length; i++) {
                    arrStr += arr[i];
                    if (i != arr.length - 1) {
                        arrStr += ",";
                    }
                }
                soDynamic.setPic(arrStr);
                soDynamic.setUid(Integer.parseInt(uid));
                soDynamicService.save(soDynamic);
                return R.success("发布成功");
            } else if (act.equals("list")) {
                Long pn2 = Long.parseLong(pn);
                Long pageSize = Long.parseLong(size);
                Page<SoDynamic> pageInfo = new Page<>(pn2, pageSize);
                LambdaQueryWrapper<SoDynamic> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.orderByDesc(SoDynamic::getAddtime);
                Page<SoDynamic> page = soDynamicService.page(pageInfo, queryWrapper);
                List<SoDynamic> records = page.getRecords();
                ArrayList<List> arrayLists = new ArrayList<>();
                List<SoDynamicDto> collect = records.stream().map((item) -> {
                    SoDynamicDto soDynamicDto = new SoDynamicDto();
                    BeanUtils.copyProperties(item, soDynamicDto);

                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    String dateString = formatter.format(item.getAddtime() * 1000L);
                    soDynamicDto.setAddtime(dateString);

                    String[] parts = item.getPic().split(",");
                    soDynamicDto.setPic(Arrays.asList(parts));
                    String[] parts2 = item.getTag().split(",");
                    soDynamicDto.setTag(Arrays.asList(parts2));

                    Integer did1 = item.getDid();//每个动态did
                    LambdaQueryWrapper<SoLikes> queryWrapper2 = new LambdaQueryWrapper<>();
                    queryWrapper2.eq(uid != null, SoLikes::getUid, uid)
                            .eq(did1 != null, SoLikes::getDid, did1);
                    List<SoLikes> list = soLikesService.list(queryWrapper2);
                    if (list != null && list.size() != 0) {
                        soDynamicDto.setZan(1);
                    }

                    Integer touid2 = item.getUid();//每个动态发布者

                    SoUser soUser = soUserService.getById(touid2);
                    String nickname = soUser.getNickname();
                    soDynamicDto.setNickname(nickname);

                    LambdaQueryWrapper<SoFocus> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(uid != null, SoFocus::getUid, uid)
                            .eq(touid2 != null, SoFocus::getTouid, touid2);
                    List<SoFocus> list1 = soFocusService.list(queryWrapper1);
                    if (list1 != null && list1.size() != 0) {
                        soDynamicDto.setGz(1);
                    }
                    return soDynamicDto;
                }).collect(Collectors.toList());
                arrayLists.add(collect);
                arrayLists.add(records);
                return R.success(arrayLists);
            } else if (act.equals("zan")) {
                LambdaQueryWrapper<SoLikes> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(uid != null, SoLikes::getUid, uid)
                        .eq(did != null, SoLikes::getDid, did);
                List<SoLikes> list = soLikesService.list(queryWrapper);
                if (list != null && list.size() != 0) {
                    soLikesService.remove(queryWrapper);
                } else {
                    SoLikes soLikes = new SoLikes();
                    soLikes.setUid(Integer.parseInt(uid));
                    soLikes.setDid(Integer.parseInt(did));
                    soLikesService.save(soLikes);
                }
                LambdaQueryWrapper<SoLikes> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(did != null, SoLikes::getDid, did);
                int count = soLikesService.count(queryWrapper2);
                SoDynamic soDynamic = new SoDynamic();
                soDynamic.setZannum(count);
                LambdaQueryWrapper<SoDynamic> queryWrapper3 = new LambdaQueryWrapper<>();
                queryWrapper3.eq(did != null, SoDynamic::getDid, did);
                soDynamicService.update(soDynamic, queryWrapper3);
                return R.success(Integer.toString(count));
            } else if (act.equals("notice")) {
                LambdaQueryWrapper<SoFocus> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(uid != null, SoFocus::getUid, uid).eq(touid != null, SoFocus::getTouid, touid);
                List<SoFocus> list = soFocusService.list(queryWrapper);
                if (list != null && list.size() != 0) {
                    soFocusService.remove(queryWrapper);
                } else {
                    SoFocus soFocus = new SoFocus();
                    soFocus.setUid(Integer.parseInt(uid));
                    soFocus.setTouid(Integer.parseInt(touid));
                    soFocusService.save(soFocus);
                }
                return R.success(touid);
            } else if (act.equals("getd")) {
                ArrayList<Map> maps = new ArrayList<Map>();

                LambdaQueryWrapper<SoDynamic> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(uid != null, SoDynamic::getUid, uid);
                int count = soDynamicService.count(queryWrapper);
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("num", Integer.toString(count));
                maps.add(hashMap);

                LambdaQueryWrapper<SoFocus> queryWrapper2 = new LambdaQueryWrapper<>();
                queryWrapper2.eq(uid != null, SoFocus::getTouid, uid);
                int count2 = soFocusService.count(queryWrapper2);
                HashMap<String, String> hashMap2 = new HashMap<String, String>();
                hashMap2.put("num2", Integer.toString(count2));
                maps.add(hashMap2);

                return R.success(maps);
            }
        }

        return R.success("");
    }
}
